package com.gopay.scheduler.job;

import com.gopay.common.constants.mail.MailLevel;
import com.gopay.common.constants.mail.MailTemplateType;
import com.gopay.common.constants.riskcontrol.RiskControlConstants;
import com.gopay.common.domain.acps.AcctMastField;
import com.gopay.common.domain.acps.AcctProd;
import com.gopay.common.domain.acps.AcpsAcctOperatLogs;
import com.gopay.common.domain.acps.TranResult;
import com.gopay.common.domain.acps.model.AcctMastBean;
import com.gopay.common.domain.mail.Send;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import com.gopay.common.util.StringTools;
import com.gopay.remote.acps.service.AcctTransRemoteService;
import com.gopay.remote.cps.mail.MailRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.dao.qulifications.OverQualificationsInfoReadDao;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * CLASSNAME:AutoGenHasOverQualificationsNotifyJob
 * Description:扫描已经过期的客户锁定其全部收款账户，并发送邮件告知
 * DATE:2018/6/21/021
 * AUTHER:PANSHICHAO
 * www.gopay.com.cn Inc.All rights reserved.
 */
public class AutoGenHasOverQualificationsNotifyJob  extends GopayBaseJob {
    @Autowired
    private OverQualificationsInfoReadDao overQualificationsInfoReadDao;
    @Resource(name="mailRemoteService")
    private MailRemoteService mailRemoteService;
    private @Value("#{webProperties['portal.url']}") String portalUrl;
    @Resource(name = "acctTransRemoteService")
    private AcctTransRemoteService acctTransRemoteService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    protected void doJobInternal() {
        Date nowDate = new Date();
        List<Object[]> resultList = overQualificationsInfoReadDao.getAllHasOverQualificationInfo(nowDate);
        if(resultList == null || resultList.isEmpty()){
            logger.info("无过期用户需要处理");
        }else{
            JSONArray json1 = JSONArray.fromObject(resultList);
            String str = json1.toString();//把json转换为String
            logger.info("即将资质过期的对象："+str);
            for(Object[] objs : resultList){
                String custId= StringTools.checkNulltoString(objs[0]);
                String email=StringTools.checkNulltoString(objs[2]);
                if(StringUtils.isNotBlank(email)){
                    List<AcctMastBean> newAcctList = new ArrayList<AcctMastBean>();
                    List<AcctMastBean> acctList = acctTransRemoteService.getAccounts(custId);
                    for(AcctMastBean acctMastBean :acctList){
                        List<Object[]> resultList1 =overQualificationsInfoReadDao.showAcctOperatorLogByAcctIdAndLastUpdTime(acctMastBean.getAcctId());
                        if(resultList1 ==null){
                            newAcctList.add(acctMastBean);
                        }else if(resultList1 !=null && !resultList1.isEmpty()){
                            String operaRes = StringTools.checkNulltoString(resultList1.get(0)[2]);
                            if(!StringUtils.equals(AcpsAcctOperatLogs.OVER_QULIFATIONS_LOCK,operaRes)){
                                newAcctList.add(acctMastBean);
                            }
                        }
                    }
                    TranResult up = new TranResult();
                    for(AcctMastBean acctMastBean : newAcctList){
                        if(AcctProd.SUBCLOUD != acctMastBean.getProdCode()){
                            Map<AcctMastField, String> accstatu = new HashMap<AcctMastField, String>();
                            accstatu.put(AcctMastField.ACC_STATUS,"F");
                            AcpsAcctOperatLogs acpsAcctOperatLogs = new AcpsAcctOperatLogs();
                            acpsAcctOperatLogs.setAcctId(acctMastBean.getAcctId());
                            acpsAcctOperatLogs.setRemark("");
                            String accStatus =acctMastBean.getAccStatusStr()+","+acctMastBean.getFrezCodeStr();
                            if ("A,NOR".equals(accStatus)) {
                                accStatus = "F,CRE";
                            } else if ("F,FUL".equals(accStatus)) {
                                accStatus = "F,FUL";
                            } else if ("F,DEB".equals(accStatus)) {
                                accStatus = "F,FUL";
                            }
                            String frezCode = accStatus.substring(accStatus.indexOf(",")+1);
                            accstatu.put(AcctMastField.FREZ_CODE,frezCode);
                            acpsAcctOperatLogs.setLockType(accStatus);
                            acpsAcctOperatLogs.setOperationType("A,NOR".equals(accStatus) ?
                                    RiskControlConstants.FRAUD_ACC_UNLOCK_TYPE : RiskControlConstants.FRAUD_ACC_LOCK_TYPE);
                            acpsAcctOperatLogs.setOperaRes(RiskControlConstants.OVER_QUALIFICATION_OPERATION);
                            acpsAcctOperatLogs.setOperId("100181");
                            up = acctTransRemoteService.updateAcctStatus(acctMastBean.getAcctId(), accstatu, acpsAcctOperatLogs);
                        }
                    }
                    if(!newAcctList.isEmpty()){
                        logger.info("开始发送邮件,客户的custId:"+custId);
                        Send send = new Send();
                        send.setReceivers(email);
                        send.setTemplate(MailTemplateType.EMAIL_HAS_QUALIFICATIONS_SEND.value);
                        send.setLevel(MailLevel.MID);
                        Map<String,Object> json = new HashMap<String,Object>(3);
                        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
                        String overBussinessTerm = "";
                        String overLegalPersonCertTerm="";
                        if(objs[3] != null){
                            Date d = (Date) objs[3];
                            if(d.getTime() - nowDate.getTime() <0){
                                overLegalPersonCertTerm = format.format(d);
                            }
                        }
                        if(objs[4] != null){
                            Date d = (Date)objs[4];
                            if(d.getTime() - nowDate.getTime() <0){
                                overBussinessTerm=format.format(d);
                            }
                        }
                        if(org.apache.commons.lang3.StringUtils.isNotBlank(overBussinessTerm)){
                            String overBussinessTermVal = "<li>营业执照已于"+overBussinessTerm+"到期</li>";
                            json.put("overBussinessTermVal",overBussinessTermVal);
                        }else{
                            json.put("overBussinessTermVal","");
                        }
                        if(org.apache.commons.lang3.StringUtils.isNotBlank(overLegalPersonCertTerm)){
                            String overLegalPersonCertTermVal = "<li>法定代表人证件已于"+overLegalPersonCertTerm +"到期</li>";
                            json.put("overLegalPersonCertTermVal",overLegalPersonCertTermVal);
                        }else{
                            json.put("overLegalPersonCertTermVal","");
                        }
                        json.put("replacethistotheLogoAddr", portalUrl);
                        send.setContent(JSONObject.fromObject(json).toString());
                        int i =mailRemoteService.addMailTask(send);
                        logger.info("邮件发送ID为："+i);
                    }else{
                        logger.info("已经存在资质过期锁定记录，无需再在锁定");
                    }
                }
            }
        }

    }


}
